package club.xinghe.servlet.student;

import club.xinghe.biz.ExamBiz;
import club.xinghe.biz.ScoreBiz;
import club.xinghe.entity.Student;
import club.xinghe.util.JsonServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/student/StuScoreServlet")
public class StuScoreServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ExamBiz examBiz=new ExamBiz();
        HttpSession session=request.getSession();
        String stuAnswer[]=request.getParameterValues("answers");//接收前台传递的学生选择的答案数组
        int eid= (int) session.getAttribute("eid");//获取session试卷的tid
        String answer[]=examBiz.getOneAnswer(eid);
        System.out.println("学生答案");
        for(String s:stuAnswer){
            System.out.print(s+",");
        }
        System.out.println("------------------------------");
        System.out.println("正确答案");
        for (String a:answer){
            System.out.print(a+",");
        }
        System.out.println("------------------------------");
        float d=0;float x=0;
        for(int i=0;i<answer.length;i++){
            if(answer[i].trim().equals(stuAnswer[i])){
                d++;
            }else{
                x++;
            }
        }
        int score=(int)(d/(d+x)*100);
        //获取到sid,eid,zid,然后将成绩存入数据库
        Student student= (Student) session.getAttribute("student");
        System.out.println("名字"+student.getsId()+"zid"+student.getZy().getzId());

        int sid=student.getsId();//得到学生的ID
        int cj=score;
        int zid=student.getZy().getzId();//得到学生所在专业的ID
        System.out.println("sid"+sid+"eid"+eid+"cj"+cj+"zid"+zid);
        ScoreBiz scoreBiz=new ScoreBiz();
        int flag=scoreBiz.putScore(sid,eid,cj,zid);
        if (flag>0){
            System.out.println("插入成绩成功！");
        }


        //回调给页面
        Student stu= (Student) session.getAttribute("student");
        Map<String,Object> map=new HashMap<>();
        map.put("stu",stu);
        map.put("score",score);
        JsonServlet.getJson(request,response,map);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
